package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.mes.entity.MesProductionPlanOrderDetail;
import org.jeecg.modules.mes.mapper.MesProductionPlanOrderDetailMapper;
import org.jeecg.modules.mes.service.IMesProductionPlanOrderDetailService;
import org.jeecg.modules.oms.entity.ProductSalesOrderDetail;
import org.jeecg.modules.oms.service.IProductSalesOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 生产计划订单明细关联服务实现
 * @Author: jeecg-boot
 * @Date: 2025-08-30
 * @Version: V2.0
 */
@Service
@Slf4j
public class MesProductionPlanOrderDetailServiceImpl extends ServiceImpl<MesProductionPlanOrderDetailMapper, MesProductionPlanOrderDetail> implements IMesProductionPlanOrderDetailService {

    @Autowired
    private MesProductionPlanOrderDetailMapper planOrderDetailMapper;

    @Autowired
    private IProductSalesOrderDetailService orderDetailService;

    @Override
    public List<MesProductionPlanOrderDetail> getOrderDetailsByPlanId(String planId) {
        try {
            return planOrderDetailMapper.getOrderDetailsByPlanId(planId);
        } catch (Exception e) {
            log.error("获取计划关联订单明细失败: planId={}", planId, e);
            throw new JeecgBootException("获取计划关联订单明细失败");
        }
    }

    @Override
    public List<MesProductionPlanOrderDetail> getPlansByOrderDetailId(String orderDetailId) {
        try {
            return planOrderDetailMapper.getPlansByOrderDetailId(orderDetailId);
        } catch (Exception e) {
            log.error("获取订单明细关联计划失败: orderDetailId={}", orderDetailId, e);
            throw new JeecgBootException("获取订单明细关联计划失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreatePlanOrderDetails(String planId, List<String> orderDetailIds) {
        try {
            if (orderDetailIds == null || orderDetailIds.isEmpty()) {
                return true;
            }

            // 检查是否可以添加这些订单明细
            if (!canAddOrderDetailsToPlan(planId, orderDetailIds)) {
                throw new JeecgBootException("部分订单明细不能添加到计划中");
            }

            // 获取订单明细信息
            List<ProductSalesOrderDetail> orderDetails = orderDetailService.listByIds(orderDetailIds);
            
            // 创建关联记录
            List<MesProductionPlanOrderDetail> planOrderDetails = orderDetails.stream()
                .map(orderDetail -> {
                    MesProductionPlanOrderDetail planOrderDetail = new MesProductionPlanOrderDetail();
                    planOrderDetail.setPlanId(planId);
                    planOrderDetail.setOrderId(orderDetail.getOrderId());
                    planOrderDetail.setOrderDetailId(orderDetail.getId());
                    planOrderDetail.setOrderNo(orderDetail.getOrderId()); // 使用orderId作为订单号
                    planOrderDetail.setProductInfo(orderDetail.getWindowSeries()); // 使用门窗系列作为产品信息
                    planOrderDetail.setProductCode(orderDetail.getWindowNo()); // 使用门窗窗号作为产品编码
                    planOrderDetail.setProductName(orderDetail.getWindowSeries()); // 使用门窗系列作为产品名称
                    planOrderDetail.setProductSpec(orderDetail.getWindowColor()); // 使用门窗颜色作为产品规格
                    planOrderDetail.setPlanQuantity(orderDetail.getQuantity());
                    planOrderDetail.setActualQuantity(0);
                    planOrderDetail.setStatus(0); // 待生产
                    planOrderDetail.setPriority(2); // 默认中等优先级
                    planOrderDetail.setCreateTime(new Date());
                    return planOrderDetail;
                })
                .collect(Collectors.toList());

            return this.saveBatch(planOrderDetails);
        } catch (Exception e) {
            log.error("批量创建计划订单明细关联失败: planId={}, orderDetailIds={}", planId, orderDetailIds, e);
            throw new JeecgBootException("批量创建计划订单明细关联失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderDetailProgress(String planId, String orderDetailId, Integer actualQuantity) {
        try {
            // 获取计划数量
            LambdaQueryWrapper<MesProductionPlanOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MesProductionPlanOrderDetail::getPlanId, planId)
                       .eq(MesProductionPlanOrderDetail::getOrderDetailId, orderDetailId);
            
            MesProductionPlanOrderDetail planOrderDetail = this.getOne(queryWrapper);
            if (planOrderDetail == null) {
                throw new JeecgBootException("未找到对应的计划订单明细关联记录");
            }

            // 确定状态
            Integer status = 0; // 待生产
            if (actualQuantity > 0) {
                if (actualQuantity >= planOrderDetail.getPlanQuantity()) {
                    status = 2; // 已完成
                } else {
                    status = 1; // 生产中
                }
            }

            return planOrderDetailMapper.updateOrderDetailProgress(planId, orderDetailId, actualQuantity, status) > 0;
        } catch (Exception e) {
            log.error("更新订单明细生产进度失败: planId={}, orderDetailId={}, actualQuantity={}", 
                planId, orderDetailId, actualQuantity, e);
            throw new JeecgBootException("更新订单明细生产进度失败: " + e.getMessage());
        }
    }

    @Override
    public MesProductionPlanOrderDetail getPlanOrderDetailStats(String planId) {
        try {
            return planOrderDetailMapper.getPlanOrderDetailStats(planId);
        } catch (Exception e) {
            log.error("获取计划订单明细统计失败: planId={}", planId, e);
            throw new JeecgBootException("获取计划订单明细统计失败");
        }
    }

    @Override
    public boolean canAddOrderDetailsToPlan(String planId, List<String> orderDetailIds) {
        try {
            // 检查订单明细是否已经关联到其他计划
            for (String orderDetailId : orderDetailIds) {
                List<MesProductionPlanOrderDetail> existingPlans = getPlansByOrderDetailId(orderDetailId);
                // 过滤掉当前计划
                existingPlans = existingPlans.stream()
                    .filter(plan -> !planId.equals(plan.getPlanId()))
                    .collect(Collectors.toList());
                
                if (!existingPlans.isEmpty()) {
                    log.warn("订单明细已关联到其他计划: orderDetailId={}, existingPlanIds={}", 
                        orderDetailId, existingPlans.stream().map(MesProductionPlanOrderDetail::getPlanId).collect(Collectors.toList()));
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            log.error("检查订单明细是否可添加失败: planId={}, orderDetailIds={}", planId, orderDetailIds, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeOrderDetailsFromPlan(String planId, List<String> orderDetailIds) {
        try {
            LambdaQueryWrapper<MesProductionPlanOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MesProductionPlanOrderDetail::getPlanId, planId);
            queryWrapper.in(MesProductionPlanOrderDetail::getOrderDetailId, orderDetailIds);
            
            return this.remove(queryWrapper);
        } catch (Exception e) {
            log.error("移除计划订单明细失败: planId={}, orderDetailIds={}", planId, orderDetailIds, e);
            throw new JeecgBootException("移除计划订单明细失败");
        }
    }

    @Override
    public List<Map<String, Object>> getOrderDetailsByIds(List<String> orderDetailIds) {
        try {
            if (orderDetailIds == null || orderDetailIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            List<Map<String, Object>> result = this.baseMapper.getOrderDetailsByIds(orderDetailIds);
            
            log.info("通过Mapper查询获取订单明细成功，查询条件: {}, 结果数量: {}", orderDetailIds, result.size());
            return result;
            
        } catch (Exception e) {
            log.error("根据ID列表获取订单明细失败: orderDetailIds={}", orderDetailIds, e);
            throw new JeecgBootException("获取订单明细失败: " + e.getMessage());
        }
    }
}
